<!--
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-20 00:33:55
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-04-20 11:52:10
 * @FilePath: /free-learning/src/views/review/course-review-audit/index.vue
 * @Description: 课程评价审核页面
-->
<script setup lang="ts">
import { AUDIT_OPTIONS } from "@/enums/AuditEnum";
import {
  quertReviewPage,
  auditReview,
  deleteCourseReview,
  getAuditHistory,
} from "@/api/review/course-review";
import { Search, Refresh } from "@element-plus/icons-vue";
import type { CourseReview } from "@/api/review/course-review/type";
import { ElMessageBox } from "element-plus";
import { getCourseListByConsultantId } from "@/api/course/course-mange";
import UserAPI from "@/api/system/user";
import type { CourseInfo } from "@/api/course/course-mange/type";
import { AuditEnum } from "@/enums/AuditEnum";

defineOptions({
  name: "CourseReviewAudit",
});

// 查询条件
const queryForm = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: undefined,
  courseId: undefined,
  consultantId: undefined,
  status: undefined,
});

// 表格数据
const tableData = ref<CourseReview[]>([]);
const total = ref(0);
const loading = ref(false);

// 咨询师列表
const consultantOptions = ref<OptionType[]>([]);
const consultantLoading = ref(false);
// 课程列表
const courseList = ref<CourseInfo[]>([]);
const courseLoading = ref(false);

// 审核对话框
const auditDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: undefined as number | undefined,
    status: 2,
    auditInfo: "",
  },
  rules: {
    auditInfo: [
      { required: true, message: "请输入审核不通过原因", trigger: "blur" },
      { min: 5, message: "审核原因不能少于5个字符", trigger: "blur" },
    ],
  },
});

// 审核历史对话框
const historyDialog = reactive({
  visible: false,
  loading: false,
  list: [] as any[],
  currentReview: null as CourseReview | null,
});

// 获取咨询师列表
const fetchConsultantOptions = async () => {
  try {
    consultantLoading.value = true;
    const res = await UserAPI.getConsultantOptions();
    consultantOptions.value = res;
  } finally {
    consultantLoading.value = false;
  }
};

// 获取课程列表
const fetchCourseList = async () => {
  try {
    courseLoading.value = true;
    const res = await getCourseListByConsultantId({
      consultantId: queryForm.value.consultantId,
    });
    courseList.value = res;
  } finally {
    courseLoading.value = false;
  }
};

// 监听咨询师变化
watch(
  () => queryForm.value.consultantId,
  (newVal) => {
    courseList.value = [];
    queryForm.value.courseId = undefined;
    fetchCourseList();
  }
);

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const res = await quertReviewPage(queryForm.value);
    tableData.value = res.records;
    total.value = res.total;
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

// 处理页码变化
const handleCurrentChange = (page: number) => {
  queryForm.value.pageNum = page;
  fetchData();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  queryForm.value.pageSize = size;
  queryForm.value.pageNum = 1;
  fetchData();
};

// 处理查询
const handleQuery = () => {
  queryForm.value.pageNum = 1;
  fetchData();
};

// 重置查询
const resetQuery = () => {
  queryForm.value = {
    pageNum: 1,
    pageSize: 10,
    keyword: undefined,
    courseId: undefined,
    consultantId: undefined,
    status: undefined,
  };
  fetchData();
};

// 打开审核对话框
const openAuditDialog = (row: CourseReview) => {
  auditDialog.form = JSON.parse(JSON.stringify(row));
  auditDialog.form.status = AuditEnum.FAILED;
  auditDialog.form.auditInfo = "";
  auditDialog.visible = true;
};

// 审核评价
const handleAudit = async (row: CourseReview, status: number) => {
  if (status === 2) {
    openAuditDialog(row);
    return;
  }

  try {
    await auditReview({
      ...row,
      status,
    });
    ElMessage.success("审核成功");
    fetchData();
  } catch (error) {}
};

// 提交审核
const auditFormRef = ref();
const submitAudit = async () => {
  if (!auditFormRef.value) return;

  try {
    await auditFormRef.value.validate();
    auditDialog.loading = true;

    await auditReview(auditDialog.form);

    ElMessage.success("审核成功");
    auditDialog.visible = false;
    fetchData();
  } catch (error) {
  } finally {
    auditDialog.loading = false;
  }
};

// 删除评价
const handleDelete = async (row: CourseReview) => {
  try {
    await ElMessageBox.confirm("确认删除该评价吗？", "提示", {
      type: "warning",
    });
    await deleteCourseReview(row.id);
    ElMessage.success("删除成功");
    fetchData();
  } catch (error) {}
};

// 查看审核历史
const handleHistory = async (row: CourseReview) => {
  try {
    historyDialog.loading = true;
    historyDialog.visible = true;
    historyDialog.currentReview = row;
    const res = await getAuditHistory(row.id);
    historyDialog.list = res;
  } catch (error) {
  } finally {
    historyDialog.loading = false;
  }
};

onMounted(() => {
  fetchConsultantOptions();
  fetchCourseList();
  fetchData();
});
</script>

<template>
  <div class="app-container">
    <!-- 搜索工具栏 -->
    <el-card class="mb-4 !border-none" shadow="never">
      <el-form ref="queryFormRef" :model="queryForm" inline>
        <el-form-item label="关键字" prop="keyword">
          <el-input
            v-model="queryForm.keyword"
            placeholder="请输入关键字"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="咨询师" prop="consultantId">
          <el-select
            v-model="queryForm.consultantId"
            placeholder="请选择咨询师"
            clearable
            :loading="consultantLoading"
            style="width: 200px"
          >
            <el-option
              v-for="item in consultantOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select
            v-model="queryForm.courseId"
            placeholder="请选择课程"
            clearable
            filterable
            :loading="courseLoading"
            style="width: 200px"
          >
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in AUDIT_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="!border-none" shadow="never">
      <el-table v-loading="loading" :data="tableData" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="courseName" label="课程名称" min-width="200" show-overflow-tooltip />
        <el-table-column label="评论用户" width="120" align="center">
          <template #default="{ row }">
            <div>{{ row.nickName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="comment" label="评论内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="score" label="评分" width="150" align="center">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column prop="reviewTime" label="评论时间" width="180" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'info' : row.status === 1 ? 'success' : 'danger'">
              {{ AUDIT_OPTIONS.find((item) => item.value === row.status)?.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditInfo" label="审核原因" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.status === AuditEnum.FAILED" class="text-red-500">
              {{ row.auditInfo }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 0"
              type="success"
              link
              @click="handleAudit(row, AuditEnum.PASSED)"
            >
              通过
            </el-button>
            <el-button
              v-if="row.status === 0"
              type="danger"
              link
              @click="handleAudit(row, AuditEnum.FAILED)"
            >
              拒绝
            </el-button>
            <el-button type="primary" link @click="handleHistory(row)">审核历史</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialog.visible"
      title="审核不通过原因"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="auditFormRef"
        :model="auditDialog.form"
        :rules="auditDialog.rules"
        label-width="100px"
      >
        <el-form-item label="原因" prop="auditInfo">
          <el-input
            v-model="auditDialog.form.auditInfo"
            type="textarea"
            :rows="4"
            placeholder="请输入审核不通过原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialog.visible = false">取 消</el-button>
        <el-button type="primary" :loading="auditDialog.loading" @click="submitAudit">
          确 定
        </el-button>
      </template>
    </el-dialog>

    <!-- 审核历史对话框 -->
    <el-dialog
      v-model="historyDialog.visible"
      title="审核历史"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <div v-loading="historyDialog.loading">
        <!-- 评价信息 -->
        <div class="mb-4 p-4 bg-gray-50 rounded">
          <h3 class="text-lg font-bold mb-2">评价信息</h3>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <span class="text-gray-500">课程：</span>
              <span>{{ historyDialog.currentReview?.courseName }}</span>
            </div>
            <div>
              <span class="text-gray-500">评价用户：</span>
              <span>{{ historyDialog.currentReview?.nickName }}</span>
            </div>
            <div>
              <span class="text-gray-500">评分：</span>
              <el-rate
                :model-value="historyDialog.currentReview?.rating"
                disabled
                text-color="#ff9900"
              />
            </div>
            <div>
              <span class="text-gray-500">评价时间：</span>
              <span>{{ historyDialog.currentReview?.reviewTime }}</span>
            </div>
          </div>
          <div class="mt-2">
            <span class="text-gray-500">评价内容：</span>
            <p class="mt-1">{{ historyDialog.currentReview?.comment }}</p>
          </div>
        </div>

        <!-- 历史记录 -->
        <div class="border rounded">
          <div class="p-4 bg-gray-50 border-b">
            <h3 class="text-lg font-bold">审核记录</h3>
          </div>
          <el-timeline class="p-4">
            <el-timeline-item
              v-for="(history, index) in historyDialog.list"
              :key="index"
              :type="history.status === AuditEnum.PASSED ? 'success' : 'danger'"
              :timestamp="history.createTime"
            >
              <div class="flex items-center justify-between">
                <span>
                  审核结果：
                  <el-tag
                    :type="history.status === AuditEnum.PASSED ? 'success' : 'danger'"
                    size="small"
                  >
                    {{ AUDIT_OPTIONS.find((item) => item.value === history.status)?.label }}
                  </el-tag>
                </span>
                <span class="text-gray-500">审核人：{{ history.auditorName }}</span>
              </div>
              <div v-if="history.auditInfo" class="mt-2">
                <span class="text-gray-500">审核原因：</span>
                <p class="mt-1">{{ history.auditInfo }}</p>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  :deep(.el-card__body) {
    padding-bottom: 0;
  }
}

:deep(.el-timeline-item__node--normal) {
  left: -2px;
}

:deep(.el-timeline-item__tail) {
  left: 4px;
}

:deep(.el-timeline) {
  padding-left: 16px;
}
</style>
